<?php
defined('SYSPATH') or die('No direct access allowed.');
class Service_purchaseadd {
	
	/**
	 * 采购单信息
	 * @var unknown
	 */
	protected $purchase_order;
	
	/**
	 * 得到采购单编号
	 * @return string
	 */
	static function get_purchaseorder_num()
	{

		$sql = "SELECT MAX(id) AS maxid FROM purchaseorders WHERE 1 LIMIT 1";
		$maxid = DB::query(Database::SELECT, $sql)->execute("newerp")->current();
		return  $maxid?$maxid['maxid']+1000:0;
	}
	
	/**
	 * 添加采购单
	 * @param $purchaseorder
	 * @return $this->purchase_order
	 */
	public function add_purchaseorder($purchaseorder)
	{
	    if($this->purchase_order)
		{
			return $this->purchase_order;
		}
		if($purchaseorder and is_numeric($purchaseorder))//采购单id
		{
			$this->purchase_order = $this->get_purchaseorder_by_id($purchaseorder);
		}
		elseif ($purchaseorder and is_array($purchaseorder))//添加采购单
		{
				$this->purchase_order = $this->insert_purchaseorder($purchaseorder);
		}
		
		return $this->purchase_order;
	}
	
	/**
	 * 插入采购单
	 * @param array $purchaseorder
	 * @return int | NULL
	 */
	protected function insert_purchaseorder(array $purchaseorder)
	{
		//预警生成得采购单
		if(isset($purchaseorder['createtype']) and $purchaseorder['createtype'] == 2)
		{
			$purchaseorder_insert = $this->purchase_merge($purchaseorder);//采购单
		}
		else 
		{
			$purchaseorder['createtype'] = 1;
			$purchaseorder_insert = $this->insert_purchaseorder_by_array($purchaseorder);//采购单	
		}
		
		return $purchaseorder_insert;
	}
	

	
	/**
	 * 通过数组插入采购单
	 * @param array $purchaseorder
	 * @return int | NULL
	 */
	protected function insert_purchaseorder_by_array(array $purchaseorder)
	{
        $purchaseorder_insert_data = array();

        $purchaseorder_insert_data['purchaseorder_date'] = isset($purchaseorder['purchaseorder_date'])?$purchaseorder['purchaseorder_date']:date('Y-m-d H:i:s');

        $purchaseorder_insert_data['supplier_id'] = isset($purchaseorder['supplier_id'])?$purchaseorder['supplier_id']:'';

        $purchaseorder_insert_data['pay_way'] = isset($purchaseorder['pay_way'])?$purchaseorder['pay_way']:'';
        $purchaseorder_insert_data['enterprise_dominant'] = isset($purchaseorder['enterprise_dominant'])?$purchaseorder['enterprise_dominant']:'';
        //默认-1无法确定退税类型 ，只有香港主体是非出口退税,其它出口退税
        $purchaseorder_insert_data['export_tax_rebate'] = empty($purchaseorder['enterprise_dominant'])?-1:(in_array($purchaseorder['enterprise_dominant'],array(12))?0:1);
        $purchaseorder_insert_data['transfer_type'] = isset($purchaseorder['transfer_type'])?$purchaseorder['transfer_type']:'';

        $purchaseorder_insert_data['purchase_id'] = isset($purchaseorder['purchase_id'])?$purchaseorder['purchase_id']:User::active_user()->id;
        $purchaseorder_insert_data['purchaseplaner'] = isset($purchaseorder['purchaseplaner'])?$purchaseorder['purchaseplaner']:User::active_user()->id;

        $purchaseorder_insert_data['money'] = isset($purchaseorder['money'])?$purchaseorder['money']:'';

        $purchaseorder_insert_data['remark'] .= isset($purchaseorder['remark'])?$purchaseorder['remark']:'';

        $purchaseorder_insert_data['check_man'] = isset($purchaseorder['check_man'])?$purchaseorder['check_man']:'';

        $purchaseorder_insert_data['check_time'] = isset($purchaseorder['check_time'])?$purchaseorder['check_time']:'';

        $purchaseorder_insert_data['transportation_expense'] = isset($purchaseorder['transportation_expense'])?$purchaseorder['transportation_expense']:'';
        $purchaseorder_insert_data['status'] = isset($purchaseorder['status'])?$purchaseorder['status']:10;

        //yuqing
        $purchaseorder_insert_data['store'] = isset($purchaseorder['store'])?$purchaseorder['store']:0;
        $purchaseorder_insert_data['warehouseid'] = isset($purchaseorder['store'])?$purchaseorder['store']:0;
        $purchaseorder_insert_data['transfer_hopper_id'] = isset($purchaseorder['transfer_hopper_id'])?$purchaseorder['transfer_hopper_id']:0;
        //yuqing

        $purchaseorder_insert_data['purchase_time'] = isset($purchaseorder['purchase_time'])?$purchaseorder['purchase_time']:'';

        $purchaseorder_insert_data['purchaseid'] = isset($purchaseorder['purchaseid'])?$purchaseorder['purchaseid']:'';

        $purchaseorder_insert_data['createtype'] = isset($purchaseorder['createtype'])?$purchaseorder['createtype']:'';

        $purchaseorder_insert_data['coin'] = isset($purchaseorder['coin'])?$purchaseorder['coin']:1;

        $purchaseorder_insert_data['ratetype'] = isset($purchaseorder['ratetype'])?$purchaseorder['ratetype']:0;

        $purchaseorder_insert_data['rate'] = isset($purchaseorder['rate'])?$purchaseorder['rate']:0;
        list($insert_id, $total_rows) = DB::insert('purchaseorders',array_keys($purchaseorder_insert_data))
            ->values(array_values($purchaseorder_insert_data))->execute('newerp');
        include_once(MODPATH.'/common/logs.php');
        logs::purchaseorder_log($insert_id, '创建成功');
        if($total_rows >0)
        {
            logs::write_log($insert_id,'purchaseorders/insert',1);
            $purchasesupplier_insert_data = array();
            $purchasesupplier_insert_data['poid'] = $insert_id;
            $purchasesupplier_insert_data['contact_id'] = isset($purchaseorder['contact_id'])?$purchaseorder['contact_id']:'';
            $purchasesupplier_insert_data['supplier_id'] = isset($purchaseorder['supplier_id'])?$purchaseorder['supplier_id']:'';
            $purchasesupplier_insert_data['pay_way_id'] = isset($purchaseorder['pay_way'])?$purchaseorder['pay_way']:'';
            $purchasesupplier_insert_data['payaccountinfo_id'] = isset($purchaseorder['payaccountinfo_id'])?$purchaseorder['payaccountinfo_id']:'';
            $purchasesupplier_insert_data['createtime'] = date('Y-m-d H:i:s');
            $purchasesupplier_insert_data['updatatime'] = $purchasesupplier_insert_data['createtime'];
            $purchasesupplier_insert_data['oper_id'] = isset($purchaseorder['purchase_id'])?$purchaseorder['purchase_id']:User::active_user()->id;

            list($id,$rows) = DB::insert('purchasesupplier',array_keys($purchasesupplier_insert_data))
                ->values(array_values($purchasesupplier_insert_data))
                ->execute('newerp');
            logs::write_log($id,'purchasesupplier/insert',1);
        }
        return  $total_rows>0?$insert_id:NULL;

	}
	
	
	/**
	 * 获取已经存在的采购单
	 * @param int $id
	 * @return int | NULL
	 */
	protected function get_purchaseorder_by_id($id)
	{
		$purchase_order = DB::select()
								->from('purchaseorders')
								->where('id','=',$id)
								->execute('newerp')
								->current();
		
		return  $purchase_order?$purchase_order['id']:NULL;		
	}
	
	/**
	 * 添加采购物品
	 * 
	 */
	public function add_purchaseorder_details(array $purchaseorder_details)
	{
		if($purchaseorder_details and is_array($purchaseorder_details))
		{
			$re =  $this->insert_purchaseorder_details($purchaseorder_details);
			
			//添加失败
			if(empty($re))
			{
				$this->clean_purchase($this->purchase_order);
			}
			else 
			{
// 				$this->update_purchaseorder_by_id($this->purchase_order);
				$this->update_purchaseorder_with_detail_id($re['purchaseorders'],$re['purchaseorder_details']);
			}
			
			return $re;
		}	
		
	}
	
	/**
	 * 添加采购明细
	 */
	protected function insert_purchaseorder_details(array $purchaseorder_details)
	{
		if($this->purchase_order and $purchaseorder_details)
		{
			return $this->insert_purchaseorder_details_with_purchaseorder($this->purchase_order,$purchaseorder_details);
		}
	/* 	elseif($purchaseorder_details)
		{
			return $this->insert_purchaseorder_details_without_purchaseorder($purchaseorder_details);
		} */
	}
	
	/**
	 * 已经有采购的，再添加采购明细
	 */
	protected function insert_purchaseorder_details_with_purchaseorder($purchaseorder,$purchaseorder_details)
	{
        $purchaseorder_details_insert_datas= array();
        

        $purchaseorder_details_insert_datas['purchaseorder_id'] = $purchaseorder;
        
        $purchaseorder_details_insert_datas['warehouseid'] = isset($purchaseorder_details['warehouseid'])?$purchaseorder_details['warehouseid']:0;
        
        $purchaseorder_details_insert_datas['supplier'] = isset($purchaseorder_details['supplier'])?$purchaseorder_details['supplier']:'';

        $purchaseorder_details_insert_datas['sku'] = isset($purchaseorder_details['sku'])?$purchaseorder_details['sku']:'';

        $purchaseorder_details_insert_datas['sku_name'] = isset($purchaseorder_details['sku_name'])?$purchaseorder_details['sku_name']:'';
        $purchaseorder_details_insert_datas['item'] = isset($purchaseorder_details['declarationName'])?$purchaseorder_details['declarationName']:'';

        $purchaseorder_details_insert_datas['storage_position'] = isset($purchaseorder_details['storage_position'])?$purchaseorder_details['storage_position']:'';

        $purchaseorder_details_insert_datas['sku_standard'] = isset($purchaseorder_details['sku_standard'])?$purchaseorder_details['sku_standard']:'';

        $purchaseorder_details_insert_datas['quantity'] = isset($purchaseorder_details['quantity'])?$purchaseorder_details['quantity']:'';

        $purchaseorder_details_insert_datas['single_price'] = isset($purchaseorder_details['single_price'])?$purchaseorder_details['single_price']:'';

        $purchaseorder_details_insert_datas['tax_rate'] = isset($purchaseorder_details['tax_rate'])?$purchaseorder_details['tax_rate']:'';

        //$purchaseorder_details_insert_datas['money'] = isset($purchaseorder_details['money'])?$purchaseorder_details['money']:'';

        //$purchaseorder_details_insert_datas['no_tax_money'] = isset($purchaseorder_details['no_tax_money'])?$purchaseorder_details['no_tax_money']:'';

        //$purchaseorder_details_insert_datas['tax_money'] = isset($purchaseorder_details['tax_money'])?$purchaseorder_details['tax_money']:'';

        $purchaseorder_details_insert_datas['remark'] = isset($purchaseorder_details['remark'])?$purchaseorder_details['remark']:'';
        $purchaseorder_details_insert_datas['real_tax_rate'] = isset($purchaseorder_details['real_tax_rate'])?$purchaseorder_details['real_tax_rate']:0;

        $purchaseorder_details_insert_datas['transportation_expense'] = isset($purchaseorder_details['transportation_expense'])?$purchaseorder_details['transportation_expense']:'';

        $purchaseorder_details_insert_datas['arrive_date'] = isset($purchaseorder_details['arrive_date'])?$purchaseorder_details['arrive_date']:'';

        $purchaseorder_details_insert_datas['status'] = 10;

        $purchaseorder_details_insert_datas['tax_way'] = isset($purchaseorder_details['tax_way'])?$purchaseorder_details['tax_way']:'';

        $purchaseorder_details_insert_datas['warning_quantity'] = isset($purchaseorder_details['warning_quantity'])?$purchaseorder_details['warning_quantity']:'';

        $purchaseorder_details_insert_datas['sku_unit'] = isset($purchaseorder_details['sku_unit'])?$purchaseorder_details['sku_unit']:'';

        $purchaseorder_details_insert_datas['details_date'] = isset($purchaseorder_details['details_date'])?$purchaseorder_details['details_date']:date('Y-m-d H:i:s');

        $purchaseorder_details_insert_datas['prime_cost'] = isset($purchaseorder_details['prime_cost'])?$purchaseorder_details['prime_cost']:'';
        $purchaseorder_details_insert_datas['merchandiser'] = isset($purchaseorder_details['merchandiser'])?$purchaseorder_details['merchandiser']:'';

        //单价×数量=总额
        $money_in = $purchaseorder_details_insert_datas['single_price'] * $purchaseorder_details_insert_datas['quantity'];
        $money = $money_in;
        /**
         * 外加税
         * 金额 = 成本 + 税额
         * 税额 = 成本 × 税率
         */
//        if($purchaseorder_details_insert_datas['tax_way'] == 1)
//        {
//            $money = $money_in*(1 + $purchaseorder_details_insert_datas['tax_rate']);
//        }
//
//        $tax_money =  ($money*1/(1 + $purchaseorder_details_insert_datas['tax_rate']))
//            *$purchaseorder_details_insert_datas['tax_rate'];


        $purchaseorder_details_insert_datas['money'] = $money;
//        $purchaseorder_details_insert_datas['tax_money'] = $tax_money;
//        $purchaseorder_details_insert_datas['no_tax_money'] = 	$purchaseorder_details_insert_datas['money']  - $purchaseorder_details_insert_datas['tax_money'] ;

        list($insert_id, $total_rows) = DB::insert('purchaseorder_details',array_keys($purchaseorder_details_insert_datas))
            ->values($purchaseorder_details_insert_datas)
            ->execute('newerp');
        if($total_rows>0)
        {
            return array('purchaseorders'=>$purchaseorder,'purchaseorder_details'=>$insert_id);
        }
    }
	
	/**
	 * 处理直接添加采购单的情况
	 */
	protected function insert_purchaseorder_details_without_purchaseorder($purchaseorder_details)
	{
		$purchaseorder_details['sku'] = Service_purchaseadd::sku_upper($purchaseorder_details['sku']);
		
		//获得采购单信息
		$purchaseorder = array();
		
		$purchaseorder['supplier_id'] = isset($purchaseorder_details['supplier'])?$purchaseorder_details['supplier']:NULL;//供应商id
		$purchaseorder['purchase_id'] = isset($purchaseorder_details['purchase_id'])?$purchaseorder_details['purchase_id']: User::active_user()->id;//采购员id
		
		$purchaseorder['pay_way'] = isset($purchaseorder_details['pay_way'])?$purchaseorder_details['pay_way']:NULL;//付款方式
		$purchaseorder['sku'] = isset($purchaseorder_details['sku'])?$purchaseorder_details['sku']:NULL;//sku
		$purchaseorder['createtype'] = isset($purchaseorder_details['createtype'])?$purchaseorder_details['createtype']:NULL;//创建方式

 		$purchaseorder_id = $this->purchase_merge($purchaseorder);//var_dump($purchaseorder_id);
 		
 		return $this->insert_purchaseorder_details_with_purchaseorder($purchaseorder_id, $purchaseorder_details);

	}
	
	
	/**
	 * 添加采购单物品后，更新采购单
	 * 
	 */
	protected function update_purchaseorder_by_id($purchaseorder_id)
	{
		
			//物品全部信息
			// $status = array();
			$purchaseorder_detail = DB::select(array(DB::expr('SUM(money)'),'totalmoney'),//金额
								array(DB::expr('SUM(transportation_expense)'),'totaltran'))//运费
			->from('purchaseorder_details')
			->where('purchaseorder_id','=',$purchaseorder_id)
			// ->where('status','in',$status)
			->group_by('purchaseorder_id')
			->execute('newerp')
			->current();
			
			$update_purchaseorder = array();
			$update_purchaseorder['money'] = $purchaseorder_detail['totalmoney'];//总额
			$update_purchaseorder['transportation_expense'] = $purchaseorder_detail['totaltran'];//总运费
			
			DB::update('purchaseorders')
			->set($update_purchaseorder)
			->where('id','=',$purchaseorder_id)
			->execute('newerp');
			
			return $purchaseorder_id;
		
	}
	
	/**
	 * 更新采购单信息
	 * 
	 */
	protected function update_purchaseorder_with_detail_id($purchaseorder_id,$purchaseorder_detail_id)
	{
		//原有信息
		$purchaseorder_old = DB::select()
							->from('purchaseorders')
							->where('id','=',$purchaseorder_id)
							->execute('newerp')
							->current();
		
		$purchaseorder_detail =  DB::select()
							->from('purchaseorder_details')
							->where('id','=',$purchaseorder_detail_id)
							->execute('newerp')
							->current();
		
		$purchaseorder_new = array();
		
		//金额
		$purchaseorder_new['money'] = $purchaseorder_old['money'] + $purchaseorder_detail['money'];
		
		//运费
		$purchaseorder_new['transportation_expense'] = $purchaseorder_old['transportation_expense'] 
														+ $purchaseorder_detail['transportation_expense'];
		
		//更新金额运费
		DB::update('purchaseorders')
		->set($purchaseorder_new)
		->where('id','=',$purchaseorder_id)
		->execute('newerp');
		
		//分摊运费
		Settle::settle_transportation_expense($purchaseorder_id,$purchaseorder_new['transportation_expense']);
		
		return $purchaseorder_id;
	}
	
	
	/**
	 * 合单处理，获取采购单ID
	 */
	protected function purchase_merge($purchaseorder)
	{
		  $purchase_merge = $this->get_merge_purchaseorder($purchaseorder);
	      return $purchase_merge?$purchase_merge: $this->insert_purchaseorder_by_array($purchaseorder);
	}
	
	/**
	 * 查找可以合并的采购单ID
	 */
	protected function get_merge_purchaseorder(array $purchaseorder)
	{
		// 供应商
		if(!isset($purchaseorder['supplier_id']) )
		{
			return;
		}
		
		//采购员
		if( !isset($purchaseorder['purchase_id']))
		{
			$purchaseorder['purchase_id'] = user::active_user()->id;
		}
		
		if( !isset($purchaseorder['purchase_id']))
		{
			return ;
		}
		
		$purchaseorders = DB::select('purchaseorder_details.purchaseorder_id')
		->from('purchaseorders')
		->join('purchaseorder_details')
		->on('purchaseorders.id','=','purchaseorder_details.purchaseorder_id')
		->where('purchaseorders.supplier_id','=',$purchaseorder['supplier_id'])//供应商
		->where('purchaseorders.purchase_id','=',$purchaseorder['purchase_id'])//采购员	
		->where('purchaseorders.status','=',10);//状态
		
		//创建类型
		if(isset($purchaseorder['createtype']))
		{
			$purchaseorders = $purchaseorders->where('purchaseorders.createtype','=',$purchaseorder['createtype']);
		}
		
		//sku
		if(isset($purchaseorder['sku']))
		{
			$purchaseorders = $purchaseorders->where('purchaseorder_details.sku','!=',$purchaseorder['sku']);
		}
		
		//预交期
		if(isset($purchaseorder['arrive_date']))
		{
		      $purchaseorders = $purchaseorders->where('purchaseorder_details.arrive_date','=',$purchaseorder['arrive_date']);
		}
		
		//付款方式
		if(isset($purchaseorder['pay_way']))
		{
			$purchaseorders = $purchaseorders->where('purchaseorders.pay_way','=',$purchaseorder['pay_way']);
		}
//		echo $purchaseorders;
// 		$purchaseorders->where('123','=','123');
		$purchaseorders = $purchaseorders->execute('newerp')
		->current();   
		
		return $purchaseorders?$purchaseorders['purchaseorder_id']:NULL; 
		
	}
	
	//添加采购单明细失败
	protected function clean_purchase($purchaseorder_id)
	{
		$pd = DB::select("purchaseorder_id")
			->from("purchaseorder_detail")
			->where('purchaseorder_id',"=",$purchaseorder_id)
			->execute('newerp')->as_array();
		
		//如果没有
		if(empty($re))
		{
			DB::update("purchaseorders")->set(array("status"=>100))->where("id",'=',$purchaseorder_id);
		}
	}

	//去除空格以及转换为大写
	static function sku_upper($sku)
	{
		$sku = trim($sku);
		$sku = preg_replace('# #','',$sku);
		$sku = strtoupper($sku);
		return $sku;
	}
	
	//获取数据库字段
	static function get_table_field($db_group,$table)
	{
		if($db_group and $table)
		{
			$_table_field = DB::select()->from($table)->limit(1)->execute($db_group)->current();
		}
		
		if($_table_field)
		{
			return array_keys($_table_field);
		}
		
		return NULL;
	}

	//
	static function get_data(array $keys,array $datas)
	{
		$re = array();
		if($keys and $datas)
		{
			foreach ($datas as $key => $data)
			{
				if(in_array($key, $keys))
				{
					$re[$key] = $data;
				}
			}
		}
		return $re;
	}
}
